package main

import (
"web" 
"fmt"
"rand"
"time"
"strconv"
)


func getRand(sample []int) (ret float) {
	leng := len(sample)
	for i:=0;i<len(sample);i++{
		rdex := rand.Intn(leng)
		sample[i],sample[rdex] = sample[rdex],sample[i]
		leng--
	}
	ret = 0
	cur := 0
	for i:=0;i<len(sample);i++{
		if sample[i] > cur {
			ret++
			cur = sample[i]
		}
	}
	return ret
}

func hello() string{
	return `source is  <a href = http://funx.googlecode.com/svn/trunk/date> here</a>
<form method=POST action="/date"> 
	<table border=0 cellpadding=0 cellspacing=0 > 
		<tr> <td ><input type=text name=t size=50 maxlength=2048 value="输入你认为将会碰到的多少值得动心的人(默认100)" title="Search"><td> 
		<tr> <td ><input type=text name=s maxlength=2048 value="输入取样次数(默认1000)" title="Search"><td> 
		<tr> <td><input type=submit name="btnG"  value="Submit">   <td>
	</table> 
	</form>`
}

func bye(ctx *web.Context) string{
	timeStr := ctx.Request.Params["t"]
	sampleStr := ctx.Request.Params["s"]
	times,_ := strconv.Atoui(timeStr)
	if times > 1000 {
        if times > 20000 {
            return "Hi,Chamberlain"
        }
		return "您...是种马吗?\n"
	}

    if times == 0 {
        times = 100
    }

	samples,_ := strconv.Atoui(sampleStr)
	if samples > 10000 {
		return "靠,真bt，有必要这么多次吗\n"
	}

    if samples == 0{
        samples = 1000
    }

	return fmt.Sprintf("根据%d次平均取样，在%d中挑你碰到的第%d个最好就从了吧\n",samples,times,calcRate(uint32(times),uint32(samples)))
}

func calcRate(times,samples uint32) uint32{
	//we can also use rand.Perm()
	sample := make([]int,times)
	for i:=0;i<len(sample);i++{
		sample[i] = i
	}
	//add some random trick
	var max float = 0
	rand.Seed(time.Nanoseconds())
	for i := uint32(0);i<samples;i++ {
		max += getRand(sample)
	}
	return uint32(max)/samples

}

func main(){

    web.Get("/date", hello)
    web.Post("/date", bye)
    web.RunFcgi("127.0.0.1:9002")
}

